package com.moon;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.PreferencesUtils;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class AppActivity extends BaseActivity implements OnClickListener{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app);
	
		findViewById(R.id.left).setVisibility(View.INVISIBLE);
		((TextView) findViewById(R.id.center)).setText("应用");
		
		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn3).setOnClickListener(this);
		findViewById(R.id.btn4).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch(arg0.getId())
		{
		case R.id.btn0:
		{
			JSONArray classes = JSON.parseArray(PreferencesUtils.getString(this, "classes"));
			if(classes.size() == 1)
			{
				JSONObject item = classes.getJSONObject(0);
				String name = item.getString("class_alias");
				if(name == null || name.length() == 0)
				{
					name = item.getString("school_name") + item.getString("class_name");
				}
				
				Intent intent = new Intent(AppActivity.this,CourseActivity.class);
				intent.putExtra("id", item.getString("id"));
				intent.putExtra("name", name);
				startActivity(intent);
			}
			else
			{
				startActivity(new Intent(this,ChildrenActivity.class));
			}
			break;
		}
		
		case R.id.btn4:
		{
			Intent intent = new Intent(this,UserDisActivity.class);
			intent.putExtra("userId", PreferencesUtils.getString(this, "userId"));
			startActivity(intent);	
			break;
		}
		}
	}
	
	private long exitTime = 0;
	public void exitApp() {
		if ((System.currentTimeMillis() - exitTime) > 2000) 
		{
			Toast.makeText(this, "再按一次退出 应用", Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} 
		else
		{
			finish();
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitApp();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
